package com.bxd.baodan.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.j256.ormlite.dao.Dao;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.base.SystemBarTintManager;
import com.bxd.baodan.db.DBHelper;
import com.bxd.baodan.item.MessageItem;
import com.bxd.baodan.item.PlanerBean;
import com.bxd.baodan.item.UserItem;
import com.bxd.baodan.util.AppManager;
import com.bxd.baodan.util.ETUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.SpUtil;
import com.bxd.baodan.util.StatusBarUtil;
import com.bxd.baodan.widget.IosDialog;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Field;
import java.util.List;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;


public class BaseActivity extends AppCompatActivity {

    private LinearLayout parentLinearLayout;//把父类activity和子类activity的view都add到这里
    protected BaseActivity context;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // FIXME: 17/7/31 软件盘遮挡问题
       getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        context = this;


        initBarLayout(R.layout.activity_bar);
        if (this instanceof MainActivity) {
            initImmersionBar(R.color.transparent, View.GONE);
        } else {
            initImmersionBar(0, VISIBLE); //导航栏颜色
        }

        initActionBar();
        AppManager.getInstance().addActivity(this);
    }


    public int setIsNoReadDateID(MessageItem item) {
        Dao<MessageItem, ?> dao;
        int is = 0;
        try {
            dao = DBHelper.getInstance(this).getDao(MessageItem.class);
            item.setIsread(true);
            dao.createOrUpdate(item);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return is;
    }


    /**
     * 初始化contentView
     */
    private void initBarLayout(int layoutResID) {
        ViewGroup viewGroup = (ViewGroup) findViewById(android.R.id.content);
        viewGroup.removeAllViews();
        parentLinearLayout = new LinearLayout(this);
        parentLinearLayout.setOrientation(LinearLayout.VERTICAL);
        viewGroup.addView(parentLinearLayout);
        LayoutInflater.from(this).inflate(layoutResID, parentLinearLayout, true);


    }


    /*
    *
    *沉浸式需要重写的三个方法
    * */
    @Override
    public void setContentView(int layoutResID) {

        LayoutInflater.from(this).inflate(layoutResID, parentLinearLayout, true);

    }

    @Override
    public void setContentView(View view) {

        parentLinearLayout.addView(view);
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {

        parentLinearLayout.addView(view, params);

    }

    /**
     * 沉浸式
     */
    public void initImmersionBar(int color, int visibility) {
        //当系统版本为4.4或者4.4以上时可以使用沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setTintResource(color == 0 ? R.color.white : color);
        //设置黑色字体
        if (!StatusBarUtil.setBarDarkMode(this)) {
            tintManager.setTintResource(color == 0 ? R.color.transparent_10 : color);
        }

        LinearLayout linear_bar = (LinearLayout) findViewById(R.id.bar_hint);
        linear_bar.setVisibility(visibility);
        //获取到状态栏的高度
        int statusHeight = getStatusBarHeight();
        //动态的设置隐藏布局的高度
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) linear_bar.getLayoutParams();
        params.height = statusHeight;
        linear_bar.setLayoutParams(params);


    }

    /**
     * 通过反射的方式获取状态栏高度
     *
     * @return
     */
    public int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    public void initActionBar() {
        ImageView actionBarNewBack = (ImageView) findViewById(R.id.bar_iv_back);
        actionBarNewBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void initActionBarListener(OnClickListener onClick) {
        //
        ImageView actionBarNewBack = (ImageView) findViewById(R.id.bar_iv_back);
        actionBarNewBack.setOnClickListener(onClick);
    }


    public void initHomeBar(int style) {
        // initImmersionBar(0);
        View bar_content = findViewById(R.id.bar_content);
        bar_content.setVisibility(VISIBLE);
        View line = findViewById(R.id.bar_line);
        ImageView iv_right = ((ImageView) findViewById(R.id.iv_bar_right));
        TextView title = (TextView) findViewById(R.id.bar_tv_title);
        switch (style) {
            case 0:
                findViewById(R.id.bar_iv_back).setVisibility(GONE);
                bar_content.setBackground(getResources().getDrawable(R.color.white));
                iv_right.setVisibility(GONE);
                title.setVisibility(VISIBLE);
                line.setVisibility(VISIBLE);
                break;
            case 1:
                findViewById(R.id.bar_iv_back).setVisibility(GONE);
                bar_content.setBackground(getResources().getDrawable(R.color.white));
                iv_right.setVisibility(VISIBLE);
                title.setVisibility(VISIBLE);
                line.setVisibility(VISIBLE);
                iv_right.setImageResource(R.drawable.sousuo_);
                break;
            case 2:
                // initImmersionBar(R.color.green_lab);
                findViewById(R.id.bar_iv_back).setVisibility(GONE);
                bar_content.setBackground(getResources().getDrawable(R.color.green_lab));
                iv_right.setVisibility(GONE);
                title.setVisibility(GONE);
                line.setVisibility(GONE);
                break;

            case 3:
                iv_right.setImageResource(R.drawable.sousuo_);
                break;
            case 4:
                findViewById(R.id.bar_content).setVisibility(GONE);
                break;
            case 5:
                line.setVisibility(GONE);
                break;
        }
    }


    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.fade_out);
    }

    /* 设置全屏 */
    public void setFullScreen() {
        // requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 设置标题内容
     *
     * @param title
     */
    public void setActionBarTitle(String title) {
        TextView tv_title = (TextView) findViewById(R.id.bar_tv_title);
        tv_title.setVisibility(VISIBLE);
        tv_title.setText(title);
    }

    /**
     * 设置标题内容
     *
     * @param title
     */
    public void setBarBack(String title) {
        findViewById(R.id.bar_iv_back).setVisibility(GONE);
        TextView tv_back = (TextView) findViewById(R.id.bar_tv_back);
        tv_back.setText(title);
        tv_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    /**
     * 设置button内容及监听事件
     */
    public void setActionBarButton(String text, OnClickListener listener) {
        TextView btnActionBarRight = (TextView) findViewById(R.id.tv_bar_right);
        btnActionBarRight.setVisibility(VISIBLE);
        btnActionBarRight.setText(text);
        btnActionBarRight.setOnClickListener(listener);
    }


    /**
     * 修改button的背景
     */
    public void resetActionBarButton(int resid, OnClickListener listener) {
        ImageView btnActionBarRight = (ImageView) findViewById(R.id.iv_bar_right);
        btnActionBarRight.setVisibility(VISIBLE);
        // btnActionBarRight.setText("");
        btnActionBarRight.setImageResource(resid);
        btnActionBarRight.setOnClickListener(listener);
    }


    /**
     * 提示信息
     *
     * @param message
     */
    public void showToast(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * 打开指定activity
     *
     * @param targetClass
     */
    public void openActivity(Class<?> targetClass) {
        Intent intent = new Intent(this, targetClass);
        startActivity(intent);
        this.overridePendingTransition(R.anim.slide_in_right,
                R.anim.slide_out_left);
    }

    public void openActivity(Class<?> targetClass, String[] keys, String[] values) {
        Intent intent = new Intent(this, targetClass);
        for (int i = 0; i < keys.length; i++) {
            intent.putExtra(keys[i], values[i]);
        }
        startActivity(intent);
        this.overridePendingTransition(R.anim.slide_in_right,
                R.anim.slide_out_left);
    }

    public void openActivityForResult(Class<?> targetClass, String[] keys, String[] values) {
        Intent intent = new Intent(this, targetClass);
        for (int i = 0; i < keys.length; i++) {
            intent.putExtra(keys[i], values[i]);
        }
        startActivityForResult(intent, 0);
        this.overridePendingTransition(R.anim.slide_in_right,
                R.anim.slide_out_left);
    }


    public void openActivity(Class<?> targetClass, Bundle b) {
        Intent intent = new Intent(this, targetClass);
        intent.putExtras(b);
        startActivity(intent);
        this.overridePendingTransition(R.anim.slide_in_right,
                R.anim.slide_out_left);
    }


    @Override
    protected void onResume() {
        MobclickAgent.onResume(this);
        super.onResume();
    }

    @Override
    protected void onPause() {
        MobclickAgent.onPause(this);
        super.onPause();
    }

    public EditText getEditText(int id) {
        return (EditText) findViewById(id);
    }

    public TextView getTextView(int id) {
        return (TextView) findViewById(id);
    }

    public Button getButton(int id) {
        return (Button) findViewById(id);
    }

    public ImageButton getImageButton(int id) {
        return (ImageButton) findViewById(id);
    }

    public ImageView getImageView(int id) {
        return (ImageView) findViewById(id);
    }

    public LinearLayout getLinearLayout(int id) {
        return (LinearLayout) findViewById(id);
    }

    public RelativeLayout getRelativeLayout(int id) {
        return (RelativeLayout) findViewById(id);
    }

    public ListView getListView(int id) {
        return (ListView) findViewById(id);
    }


    public String getString(EditText et) {
        return ETUtil.getString(et);
    }


    public String getString(TextView tv) {
        return tv.getText().toString().trim();
    }


    public UserItem getUser() {
        return LoginInfo.getInstance(this).getUser();
    }

    public String getUserid() {
        return getUser().getU_id();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getInstance().finishActivity(this);
    }


    public void setSearchBar() {
        findViewById(R.id.back_bar_ly).setVisibility(GONE);
        findViewById(R.id.search_view).setVisibility(VISIBLE);
    }


    public boolean loginStatus() {

        boolean isLogin = (LoginInfo.getInstance(App.getContext())
                .getUser().getU_id() != null);

        if (!isLogin) {
            Intent it = new Intent(this,
                    LoginActivity.class);
            startActivity(it);
        }

        return isLogin;
    }

    public boolean isEmpty(String str) {

        return str == null && str.isEmpty();
    }

    public void hideBar() {
        findViewById(R.id.bar_content).setVisibility(GONE);
    }


    public void showExitDialog(String content) {
        new IosDialog(this).builder()
                .setTitle(content)
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();

                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    public void getPlanerId() {
        NetUtil netUtil = new NetUtil(this, JsonApi.PLANNER_LISTS);
        netUtil.postRequest("", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {
                SpUtil.getInstance().savaString("planerJson", result);
                PlanerBean bean = new Gson().fromJson(result, PlanerBean.class);
                StringBuilder sb = new StringBuilder();
                List<PlanerBean.PlanerBean_> list = bean.data.list;
                for (int i = 0; i < list.size(); i++) {
                    if (i == list.size() - 1) {
                        sb.append(list.get(i).id);
                    } else {
                        sb.append(list.get(i).id + ",");
                    }
                }
                SpUtil.getInstance().savaString("planerId", sb.toString());
            }
        });
    }
//    }

}
